import { onUnmounted, ref } from 'vue';

import { vCode } from '@/api/login/index';

export default function userCode() {
  const codeUrlRad = ref('');
  let timer: NodeJS.Timer | null = null;

  /**
   * 获取验证码
   * @returns
   */
  const getCode = async () => {
    const data = await vCode();
    console.log(data);
    const bytes = new Uint8Array(data);
    let storeData = '';
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      storeData += String.fromCharCode(bytes[i]);
    }

    codeUrlRad.value = `data:image/png;base64,${window.btoa(storeData)}`;
    console.log(codeUrlRad.value);

    timedRefresh();
  };

  /**
   * 每过30s自动刷新二维码
   */
  const timedRefresh = () => {
    clearInterval(Number(timer));
    timer = null;
    timer = setInterval(() => {
      getCode();
    }, 30000);
  };

  /**
   * 销毁定时器
   */
  onUnmounted(() => {
    clearInterval(Number(timer));
    timer = null;
  });

  return {
    codeUrlRad,
    getCode,
  };
}
